package com.uinnova.product.eam.web.util;

import com.uinnova.project.base.diagram.util.FileFilterUtil;
import com.uino.service.util.FileUtil;
import com.uino.util.rsm.RsmUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;

/**
 * 文件写入的工具类
 */
@Component
public class DmvFileUtil {

    @Autowired
    private RsmUtils rsmUtils;

    @Value("${local.resource.space}")
    private String localPath;

    /**
     * 将字符串保存/更新 为文件，自动加上日期前缀
     *
     * @param filePath    文件名或文件相对路径
     * @param fileContent 文件内容
     * @return
     * @throws IOException
     */
    public String saveOrUpdateResource(String filePath, byte[] fileContent, boolean create) throws IOException {
        if (create) {
            filePath = Paths.get("/" + LocalDate.now(), filePath).toString();
        }

        FileUtil.writeFile(filePath, fileContent);

        return filePath;
    }

    /**
     * 保存或更新格式为base64的png文件
     *
     * @param filePath
     * @param fileContent
     * @param create
     * @return
     */
    public String saveOrUpdatePng(String filePath, String fileContent, boolean create) throws IOException {
        byte[] bs = new byte[] {};
        if (fileContent.length() >= fileContent.indexOf(";base64,") + 8) {
            String substring = fileContent.substring(fileContent.indexOf(";base64,") + 8);
            bs = Base64.decodeBase64(substring);

            filePath = this.saveOrUpdateResource(filePath, bs, create);

        }

        return filePath;
    }

    public String getResourceContent(String fileUrl) throws IOException {

        rsmUtils.downloadRsmAndUpdateLocalRsm(fileUrl);

        return FileUtils.readFileToString(new File(FileFilterUtil.parseFilePath(localPath), fileUrl));
    }

}
